﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using FaceCat;
using SkiaSharp;
using SkiaSharp.Views;
using SkiaSharp.Views.Desktop;

namespace FaceCat
{
    public class FCUIView : SKControl
    {
        public FCNative m_native;
        public WinHost m_host;
        private FCUIXml m_xml;
        public SkiaPaint m_paint;

        public void initView(FCUIXml xml, String path)
        {
            if (xml != null)
            {
                m_xml = xml;
                m_xml.createNative();
                m_native = m_xml.getNative();
                m_paint = new SkiaPaint();
                m_native.setPaint(m_paint);
                m_host = new WinHost();
                m_host.setNative(m_native);
                m_native.setHost(m_host);
                m_host.setHWnd(Handle);
                m_native.setSize(new FCSize(ClientSize.Width, ClientSize.Height));
                m_xml.loadFile(path, null);
                m_native.update();
            }
            this.PaintSurface += FCUIView_PaintSurface;
            this.Disposed += FCUIView_Disposed;
        }

        /// <summary>
        /// 尺寸改变方法
        /// </summary>
        /// <param name="e">参数</param>
        protected override void OnSizeChanged(EventArgs e)
        {
            base.OnSizeChanged(e);
            if (m_host != null)
            {
                m_native.setSize(new FCSize(ClientSize.Width, ClientSize.Height));
                m_native.update();
                Invalidate();
            }
        }

        /// <summary>
        /// 消息监听
        /// </summary>
        /// <param name="m"></param>
        protected override void WndProc(ref Message m)
        {
            try
            {
                if (m_host != null)
                {
                    if (m_host.onMessage(ref m) > 0)
                    {
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
            }
            base.WndProc(ref m);
        }

        private void FCUIView_Disposed(object sender, EventArgs e)
        {
            if (this.m_native != null)
            {
                this.m_native.delete();
                this.m_native = null;
                System.GC.Collect();
            }
        }

        private void FCUIView_PaintSurface(object sender, SKPaintSurfaceEventArgs e)
        {
            var canvas = e.Surface.Canvas;
            m_paint.m_canvas = canvas;
            FCRect clipRect = new FCRect(0, 0, m_native.getSize().cx, m_native.getSize().cy);
            m_paint.beginPaint(IntPtr.Zero, clipRect, clipRect);
            m_native.onPaint(clipRect);
            m_paint.endPaint();
        }
    }
}
